package com.cxs.plan.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cxs.plan.DTO.MenuDTO;
import com.cxs.plan.domain.entity.Menu;
import com.cxs.plan.service.MenuService;
import com.cxs.plan.mapper.MenuMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author 11756
* @description 针对表【menu(菜单列表)】的数据库操作Service实现
* @createDate 2024-03-03 22:06:54
*/
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu>
    implements MenuService{

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<MenuDTO> getMenuList() {
        List<Menu> menus = menuMapper.selectList(null);
        List<MenuDTO> allList = menus.stream().map(p -> {
            MenuDTO vo = new MenuDTO();
            BeanUtils.copyProperties(p, vo);
            return vo;
        }).collect(Collectors.toList());
        //指定根节点的parentId
        return buildChildren(null, allList);
    }

    @Override
    public void addMenu(Menu menu) {
        menuMapper.insert(menu);
    }

    @Override
    public void delMenuById(Long id) {

        menuMapper.delMenuById(id);
    }

    private List<MenuDTO> buildChildren(Integer parentId, List<MenuDTO> allList){
        List<MenuDTO> voList = new ArrayList<>();
        for (MenuDTO item : allList) {
            //如果相等
            if (Objects.equals(item.getParentId(), parentId)) {
                //递归，自己调自己
                item.setChildren(buildChildren(item.getId(), allList));
                if(item.getChildren().isEmpty()) {
                    item.setChildren(null);
                }
                voList.add(item);
            }
        }
        return voList;
    }

}




